
import os,base64
import flask
import tornado.wsgi
import tornado.httpserver
import numpy as np
from flask_cors import CORS
import cv2,sys
import json
import logging
from PIL import Image
from io import BytesIO
sys.path.append("./")
from common import log_init, NpEncoder
import tqdm,glob


class Predictor(object):
    def __init__(self,  device):
        self.device=device

    def __call__(self, images):
        h,w,c=images.shape
        assert h>50
        assert w>50
        result="hello MtrLi"
        confidence_score=0.999
        return result,confidence_score

def cv_imread(file_path):
    # 读取中文路径下的图片
    cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
    if cv_img.shape[-1] == 4:
        cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGBA2RGB)
    return cv_img





if __name__ == '__main__':

    log_path = "log/OCR_log.txt"
    # sys.path.append("../log")
    log_init(log_path)
    # os.environ["MXNET_USE_FUSION"] = "1"
    # os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"]="2"
    os.environ['CUDA_VISIBLE_DEVICES'] = "1"  # todo
    device="cuda:0"


    DEBUG = True
    PORT = 28601
    app = flask.Flask(__name__)
    CORS(app, supports_credentials=True)
    predictor = Predictor(device)
    @app.route('/recog_text', methods=['POST'])
    def net_forward():
        try:
            para = json.loads(flask.request.get_data())
            user_image = para['Pic']
            user_image = base64.b64decode(user_image)
            img_array = np.frombuffer(user_image, np.uint8)
            query_img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)
            results = predictor(query_img)
            # results = [x.decode(encoding="utf-8") for x in results]
            results = [x for x in results]
            results = results[0]

            return json.dumps({"results": results}, ensure_ascii=False), 201
        except Exception as e:
            logging.exception(e)
            print("failed")
            return flask.jsonify(str(e)), 400

    print("starting webserver...")
    if DEBUG:
        app.run(debug=False, host='0.0.0.0', port=PORT)
        # app.run(debug=True, host='0.0.0.0', port=PORT, threaded=True, processes=True)
    else:
        http_server = tornado.httpserver.HTTPServer(
            tornado.wsgi.WSGIContainer(app))
        http_server.listen(PORT, address="0.0.0.0")
        tornado.ioloop.IOLoop.instance().start()
